$(function () {
    yams.menu.select('reservedManagement');

    yams.page = {
        /**
         * 初始化页面
         */
        init: function () {

            this.initDataList();
            this.initUserList();
            this.initHouseList();

            this.initEvent();
            Dolphin.form.parse();
        },
        /**
         * 初始化页面事件
         */
        initEvent: function () {
            var me = this;
            me.prices = {};

            //新建订单
            $("#orderAdd").click(function () {
                Dolphin.form.empty('.edit-form');
                $("#rentPrice").val("0");
                $("#commission").val("0");
                $("#days").val("0");
                $('#dataModal').modal('show');
            });
            //保存订单
            $(".orderSave").click(function () {
                var ef = $(".edit-form");
                if (Dolphin.form.validate(ef)) {
                    var data = Dolphin.form.getValue(ef, '"');
                    if($("#arrivedDate").val()){//日租
                        data.arrivedDate = $("#arrivedDate").val() + " 12:00:00";
                        data.leavedDate = data.leavedDate + " 14:00:00";
                    }
                    if($("#arrivedTime").val()){//钟点
                        data.arrivedDate = data.arrivedDate + ":00";
                        data.leavedDate = data.leavedDate + ":00";
                    }
                    Dolphin.ajax({
                        url: '/api/92a5f84fb768480ba164c4bf10bb90b5',
                        type: Dolphin.requestMethod.PUT,
                        data: Dolphin.json2string(data),
                        onSuccess: function (reData) {
                            me._dataList.load();
                            $('#dataModal').modal('hide');
                        }
                    });
                }
            });

            //用户选择器
            $("#selectUser").click(function(){
                $('#userModal').modal('show');
            });
            //用户选择器查询
            $("#queryUser").click(function () {
                let d = Dolphin.form.getValue('.query-user-form');
                me._userList.query(d);
            });
            //用户确定
            $(".confirmUser").click(function(){
                let userArray = me._userList.getChecked();
                $("#userId").val(userArray[0].id);
                $("#contactName").val(userArray[0].name);
                $("#contactMobile").val(userArray[0].phone);
                $('#userModal').modal('hide');
            });

            //房屋选择器
            $("#selectHouse").click(function(){

                if($("#orderType").val()){
                    if($("#orderType").val() == 'SRM01' && (!$("#arrivedTime").val()||!$("#shortRentType").val())){
                        Dolphin.alert('请先选择入住时间和钟点类型');
                        return;
                    }else if($("#orderType").val() == 'SRM02' && !$("#arrivedDate").val()){
                        Dolphin.alert('请先选择入住日期');
                        return;
                    }else{
                        $('#houseModal').modal('show');
                    }
                }else{
                    Dolphin.alert('请先选择订单类型');
                    return;
                }
            });
            //房屋选择器查询
            $("#queryHouse").click(function () {
                let d = Dolphin.form.getValue('.query-house-form');
                me._houseList.query(d);
            });
            //房屋确定
            $(".confirmHouse").click(function(){

                let houseArray = me._houseList.getChecked();
                $("#houseId").val(houseArray[0].id);
                $("#houseName").val(houseArray[0].name);

                Dolphin.ajax({
                    url: '/api/123bc41c5fe44dfc9f396b5ace5fa123@houseId='+houseArray[0].id,
                    type: Dolphin.requestMethod.GET,
                    onSuccess: function (reData) {
                        $.each(reData.rows,function(i,obj){
                            me.prices[obj.shortRentType] = obj.dayPrice;
                        });

                        //根据订单类型
                        var orderTypeVal = $("#orderType").val();
                        var price;
                        if(orderTypeVal == 'SRM01') {//钟点房
                            var rentTypeVal = $("#shortRentType").val();
                            price = me.prices[rentTypeVal];
                        }else if(orderTypeVal == 'SRM02'){//日租
                            price = Dolphin.accMul(me.prices['SRT00'],$("#days").val());
                        }
                        $("#rentPrice").val(price).change();
                        $('#houseModal').modal('hide');
                    }
                });
            });

            //选择入住退房日期
            $('#pickRangeDate').dateRangePicker({
                separator : ' to ',
                inline : false,
                container : '#dayContainer',
                getValue : function()
                {
                    if ($('#arrivedDate').val() && $('#leavedDate').val() )
                        return $('#arrivedDate').val() + ' to ' + $('#leavedDate').val();
                    else
                        return '';
                },
                setValue: function(s,s1,s2)
                {
                    $('#arrivedDate').val(s1);
                    $('#leavedDate').val(s2);
                    $("#days").val(Dolphin.strDateDifference(s1,s2));
                }
            });
            //切换订单类型
            $("#orderType").change(function(){

                var orderTypeVal = $(this).val();
                if(orderTypeVal == 'SRM01'){
                    $("#hourContainer").show();
                    $("#dayContainer").hide();
                }else if(orderTypeVal == 'SRM02'){
                    $("#hourContainer").hide();
                    $("#dayContainer").show();
                }else{
                    $("#hourContainer").hide();
                    $("#dayContainer").hide();
                }
                $(".orderRelStr").each(function () {
                    $(this).val("");
                });
                $(".orderRelNum").each(function () {
                    $(this).val("0");
                });
            });

            //钟点类型切换
            $("#shortRentType").change(function(){
                var rentTypeVal = $(this).val();

                var arrivedTimeStr = $("#arrivedTime").val();
                var arrivedTime = Dolphin.string2date(arrivedTimeStr,"yyyy-MM-dd hh:mm");

                var leaveDateStr = '';
                var leaveDate = new Date();
                if(rentTypeVal == 'SRT03'){
                    leaveDate = Dolphin.calcDate(arrivedTime, 'h', 3);
                    leaveDateStr = Dolphin.date2string(leaveDate,"yyyy-MM-dd hh:mm");
                }else if(rentTypeVal == 'SRT05'){
                    leaveDate = Dolphin.calcDate(arrivedTime, 'h', 5);
                    leaveDateStr = Dolphin.date2string(leaveDate,"yyyy-MM-dd hh:mm");
                }else if(rentTypeVal == 'SRT08'){
                    leaveDate = Dolphin.calcDate(arrivedTime, 'h', 8);
                    leaveDateStr = Dolphin.date2string(leaveDate,"yyyy-MM-dd hh:mm");
                }else{
                    leaveDate = Dolphin.calcDate(arrivedTime, 'd', 1);
                    leaveDateStr = Dolphin.date2string(leaveDate,"yyyy-MM-dd") + " 12:00";
                }
                $("#leavedDate").val(leaveDateStr);

            });
            //价格变动，自动计算佣金
            $("#rentPrice").change(function(){
                var rentPrice = $(this).val() || '0';
                Dolphin.ajax({
                    url: '/api/5b8e27d5bb9547f48235bd70aea199b9@code=systemConfig',
                    type: Dolphin.requestMethod.GET,
                    onSuccess: function (reData) {
                        if(reData.rows){
                            $.each( reData.rows, function(i, n){
                                if(n.code == 'commission'){
                                    $("#commission").val(Dolphin.accMul(rentPrice,n.name));
                                }
                            });
                        }
                    }
                });
            });

            //查询
            $(".btn-query").click(function () {
                me._dataList.load(null,Dolphin.form.getValue('.query-form'))
            });

        },

        initDataList: function () {
            let me = this;
            me._dataList = new Dolphin.LIST({
                panel: "#dataList",
                idField: 'id',
                queryParams: {
                    house_account_obj_ae : yams.context.checkAdmin()
                },
                columns: [{
                    code: 'userId',
                    hidden: true
                },{
                    code: 'contactName',
                    title: '联系姓名',
                    formatter: function(val, row, index){
                        return '<a class="showUserDetail" data-userid="'+row.userId+'" href="javascript:;">'+val+'</a>';
                    }
                }, {
                    code: 'contactMobile',
                    title: '联系手机',
                    width: '150px'
                }, {
                    code: 'house.name',
                    title: '房屋名称'
                }, {
                    code: 'arrivedDate',
                    title: '入住时间',
                    width: '120px',
                    formatter:function (val) {
                        if(val)
                            return val.substr(0,10);
                    }
                },{
                    code: 'leavedDate',
                    title: '退房时间',
                    width: '120px',
                    formatter:function (val) {
                        if(val)
                            return val.substr(0,10);
                    }
                }, {
                    code: 'rentPrice',
                    title: '价格',
                    width: '120px'
                },{
                    code: 'statusName',
                    title: '预订状态',
                    width: '120px'
                },{
                    code: 'id',
                    title: '&nbsp;',
                    width: '220px',
                    formatter: function (val, row, index) {

                        var confirmBtnStr = '';
                        var cancelBtnStr = '<a class="btn btn-outline btn-circle btn-sm dark orderCancel" href="javascript:;">' +
                            '<input type="hidden" value="'+row.id+'"/><i class="fa fa-trash-o"></i>取消</a>';
                        if(row.orderStatus == 'OS00'){
                            confirmBtnStr = '<a class="btn btn-outline btn-circle btn-sm green orderConfirm" ' +
                                'data-id="'+row.id+'" data-userid="'+row.userId+'" href="javascript:;">' +
                                '<i class="fa fa-check"></i>确认</a>';
                        }
                        return confirmBtnStr
                            + yams.buttons.edit({
                                id: row.id
                            })
                            + cancelBtnStr;
                    }
                }],
                multiple: true,
                rowIndex: true,
                checkbox: true,
                ajaxType: Dolphin.requestMethod.POST,
                url: '/api/92a5f84fb768480ba164c4bf10bb90b5',
                pagination: true,
                onLoadSuccess: function () {
                    yams.buttons.editCallback('e42ad9a6eb584b5c88cbdfa00ee72e41', 'id', function (data) {
                        let da = data.value;

                        var orderTypeVal = $("#orderType").val();
                        if(orderTypeVal == 'SRM01'){
                            $("#hourContainer").show();
                            $("#dayContainer").hide();
                            $("#arrivedTime").val(da.arrivedDate.substr(0,16));
                        }else if(orderTypeVal == 'SRM02'){
                            $("#hourContainer").hide();
                            $("#dayContainer").show();
                            $("#arrivedDate").val(da.arrivedDate.substr(0,10));
                            $("#leavedDate").val(da.leavedDate.substr(0,10));
                        }else{
                            $("#hourContainer").hide();
                            $("#dayContainer").hide();
                        }

                        $('#dataModal').modal('show');
                    });

                    //确认订单
                    $('.orderConfirm').click(function () {
                        var id = $(this).data("id");

                        Dolphin.confirm('确认订单？', {
                            callback: function (flag) {
                                if (flag) {
                                    Dolphin.ajax({
                                        url: '/api/e42ad9a6eb584b5c88cbdfa00ee06121@id='+id,
                                        type: Dolphin.requestMethod.PUT,
                                        onSuccess: function (reData) {

                                            Dolphin.ajax({
                                                url: '/api/123df51d6af845aeb13db4608eb89778',
                                                type: Dolphin.requestMethod.POST,
                                                data: Dolphin.json2string({ properties : { id : id }}),
                                                onSuccess: function(reData){

                                                    var obj = reData.value.properties;
                                                    console.log(obj);
                                                            var openid = obj.weChat;
                                                            //管理员确认短租订单后微信消息给客户
                                                            var msgData = {
                                                                "url" : "http://"+Dolphin.wechatUrl+"/yams/view/myShortRent?openId="+openid,
                                                                "openid" : openid,
                                                                "first" : "尊敬的客户，您好！管理员已确认您的订单，请在12小时内完成支付",
                                                                "keyword1" : obj.apartmentName+"(房间号："+ obj.houseNumber +")",
                                                                "keyword2" : obj.arrivedDate,
                                                                "keyword3" : obj.leavedDate,
                                                                "keyword4" : obj.rentPrice,
                                                                "keyword5" : '短租',
                                                                "remark" : "若有疑问请与管理员("+obj.managerName+","+obj.managerPhone+")联系"
                                                            }
                                                            Dolphin.ajax({
                                                                url: '/wexin/sendPayMsg',
                                                                type: Dolphin.requestMethod.POST,
                                                                data: Dolphin.json2string(msgData),
                                                                onSuccess: function (reData) {
                                                                    me._dataList.load();
                                                                }
                                                            });
                                                }
                                            });
                                        }
                                    });
                                }
                            }
                        })
                    });

                    //取消订单
                    $('.orderCancel').click(function () {
                        var id = $(this).children().val();
                        Dolphin.confirm('取消订单？', {
                            callback: function (flag) {
                                if (flag) {
                                    Dolphin.ajax({
                                        url: '/api/e42ad9a6eb584b5c88cbdfa00ee06122@id='+id,
                                        type: Dolphin.requestMethod.DELETE,
                                        onSuccess: function (reData) {
                                            me._dataList.load();
                                        }
                                    });
                                }
                            }
                        })
                    });

                    //看客户具体信息
                    $('.showUserDetail').click(function(){
                        var _this = $(this);
                        Dolphin.ajax({
                            url: '/api/0d644ca2f7394092b84a1fb0c7aa0821@id='+_this.data('userid'),
                            type: Dolphin.requestMethod.GET,
                            onSuccess: function (reData) {

                                $("#usercode").html(reData.value.code);
                                $("#useridCard").html(reData.value.idCard);
                                $("#userintroducer").html(reData.value.introducer);
                                $("#username").html(reData.value.name);
                                $("#userphone").html(reData.value.phone);
                                $("#usersex").html(reData.value.sex);
                                $("#userstatus").html(reData.value.status == '1' ? '启用' : '禁用');

                                $("#usericFrontImg").attr('src',reData.value.icFrontImg);
                                $("#usericBackImg").attr('src',reData.value.icBackImg);
                                $("#useravatarImg").attr('src',reData.value.avatarImg);

                                $('#userDetailModal').modal('show');

                            }
                        });

                    });
                }
            });
        },

        initUserList: function () {
            let me = this;
            me._userList = new Dolphin.LIST({
                panel: "#userList",
                idField: 'id',
                columns: [{
                    code: 'name',
                    title: '会员名称'
                }, {
                    code: 'code',
                    title: '会员编码'
                }, {
                    code: 'phone',
                    title: '联系方式'
                }, {
                    code: 'idCard',
                    title: '身份证号'
                }, {
                    code: 'sex',
                    title: '性别',
                    formatter: function (val) {
                        return val;
                    }
                }],
                multiple: false,
                rowIndex: true,
                checkbox: true,
                pagination: true,
                ajaxType: Dolphin.requestMethod.POST,
                url: '/api/8f7def63cc5845468b2c65a69abb0664',
                onLoadSuccess: function () {
                }
            });
        },

        initHouseList: function () {
            let me = this;
            this._houseList = new Dolphin.LIST({
                panel: '#houseList',
                idField: 'id',
                queryParams:{
                    status : 1
                },
                columns: [{
                    code: 'name',
                    title: '名称'
                }, {
                    code: 'houseType',
                    title: '户型',
                    formatter: function (val) {
                        return Dolphin.enum.getEnumText("houseType", val);
                    }
                }, {
                    code: 'floor',
                    title: '楼层'
                }, {
                    code: 'area',
                    title: '面积'
                }, {
                    code: 'monthly',
                    title: '月租'
                }, {
                    code: 'recommend',
                    title: '推荐',
                    formatter: function (val) {
                        return val ? "是" : "否";
                    }
                }, {
                    code: 'statusName',
                    title: '状态'
                }],
                multiple: false,
                rowIndex: true,
                checkbox: true,
                pagination: true,

                ajaxType: Dolphin.requestMethod.POST,
                url: '/api/9651431c68a04d54a22f1e2e7faf827b',
                onLoadSuccess: function (data) {
                }
            });
        },

        /**
         * 一些页面DOM对象和事件的销毁
         */
        destroy: function () {
        }
    };
});